package com.terry.proxy.common;
 
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 译码器
 *
 * @author allen
 * @date 2022/12/07
 */
public class MsgDecoder extends LengthFieldBasedFrameDecoder {
 
	public MsgDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
			int initialBytesToStrip) {
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
	}

	@Override
	protected Msg decode(ChannelHandlerContext ctx, ByteBuf in2) throws Exception {
		ByteBuf in = (ByteBuf) super.decode(ctx, in2);
		if (in == null) {
			return null;
		}
 
		if (in.readableBytes() < 4) {
			return null;
		}

		Msg msg = new Msg();
		// 数据长度
		int dataLength = in.readInt();
		// 数据类型
		int typeLength = in.readInt();
		byte[] types = new byte[typeLength];
		in.readBytes(types);
		msg.setType(new String(types));
		// 头消息
		int headerLength = in.readInt();
		byte[] heads = new byte[headerLength];
		in.readBytes(heads);
		msg.setHeader(JSONUtil.toBean(new String(heads), Msg.Header.class));
		//去除数据前9位重新写入buf
		byte[] data = new byte[dataLength - 4 - 4 - typeLength - 4 - headerLength];
		in.readBytes(data);
		msg.setData(data);
		in.release();
		return msg;
	}
}